#include<iostream>
#include<cstring>
#include<algorithm>
#include<queue>
#include<unordered_map>
using namespace std;

int bfs(string start)
{
    string end = "12345678x";
    unordered_map<string,int> d;
    d[start] = 0;
    queue<string> q;
    q.push(start);
    int dx[] = { 1  , 0 , -1 ,0 } ;
    int dy[] = { 0 , 1 , 0 , -1};
    while(!q.empty())
    {
        string t = q.front();
        if(t == end) return d[t];
        q.pop();
        int distance = d[t] , index = t.find('x');
        int x = index / 3 , y = index % 3;
        for(int i = 0 ; i <  4 ; i++)
        {
            int a = x + dx[i] , b = y + dy[i];
            if(a >= 0 && a < 3 && b >= 0 && b < 3)
            {
                swap(t[index],t[a*3+b]);
                if(!d.count(t))
                {
                    q.push(t);
                    d[t] = distance + 1;
                }
                swap(t[index],t[a*3+b]);
            }
        }
    }
    return -1;
}

int main()
{
    string start;
    for(int i = 0 ; i < 9 ; i++)
    {
        char ch;
        cin >> ch ;
        start += ch;
    }
    cout << bfs(start) << endl;
    return 0;
}